package com.dede.mcp_tool;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/**
 * Created by Hsh
 * in 2017/4/29 029 2:01 下午 on ACER-PC computer.
 * doc.
 * 用于读取Apk中的渠道信息
 */
public class AndroidMCPTools {

    /*
    android {
        ...
        signingConfigs {
             release {
                 // 如果要支持最新版的系统 Android 7.0
                 // 这一行必须加，否则安装时会提示没有签名
                 // 作用是只使用旧版签名，禁用V2版签名模式
                 v2SigningEnabled false
             }
        }
    }
     */

    public static final String CHARSET_NAME = "UTF-8";

    public static final String SIGN = "Channel";//务必确保和apk内的标识相同

    /**
     * 读取数据
     * 由于zipFile.getComment()添加于jdk1.7，为了兼容安卓低版本，需要手动读取
     *
     * @param path 文件路径
     * @throws IOException
     */
    public static String read(File path) {
        String channel = null;
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(path, "r");
            byte[] bytes = SIGN.getBytes(CHARSET_NAME);
            long index = raf.length() - bytes.length;
            readFully(raf, index, bytes);//读取标识位
            if (!SIGN.equals(new String(bytes, CHARSET_NAME))) {//标识位不正确
                return channel;
            }

            bytes = new byte[2];
            index -= bytes.length;
            readFully(raf, index, bytes);//读取内容长度
            int contentLength = stream2Short(bytes, 0);

            bytes = new byte[contentLength];
            index -= contentLength;
            readFully(raf, index, bytes);
            channel = new String(bytes, CHARSET_NAME);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(raf);
        }
        return channel;
    }

    /**
     * 字节数组转换成short（小端序）
     *
     * @param stream
     * @param offset
     * @return
     */
    private static int stream2Short(byte[] stream, int offset) {
        ByteBuffer buffer = ByteBuffer.allocate(2);
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        buffer.put(stream[offset]);
        buffer.put(stream[offset + 1]);
        return buffer.getShort(0);
    }

    private static void readFully(RandomAccessFile raf, long index, byte[] data) throws IOException {
        raf.seek(index);
        raf.readFully(data);
    }

    /**
     * 关闭数据流
     *
     * @param closeable
     */
    private static void close(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
            }
        }
    }
}
